//导入模块
const ws = require("ws");
const RandomAPI = require('../utils/random_utils');

const random = new RandomAPI();

//创建服务器
var wsServer = new ws.Server({
    host: global.localIP,
    port: global.wsPort,
}, () => {
    console.log(`启动成功 : ws://${global.localIP}:${global.wsPort}/`)
});

// 广播
wsServer.broadcast = function broadcast(str) {
    wsServer.clients.forEach(function each(client) {
        client.send(str);
    });
};

// 发送
wsServer.send = function send(id, str) {
    wsServer.clients.forEach(function each(client) {
        if (client.clientId == id) {
            client.send(str);
        }
    });
};

//建立连接后
wsServer.on('connection', function connection(client) {
    client.clientId = random.uniqueId()
    console.log(`${client.clientId} from server: connection `);

    /// 客户端收到消息事件
    client.on('message', function incoming(message) {
        try {
            var data = JSON.parse(message);
            switch (data.type) {
                case 'loginInfo':
                    
                    var str = JSON.stringify({
                        "msg": client.clientId,
                        "type": data.type
                    });
                    wsServer.broadcast(str);
                    break;
                case 'chatInfo':
                    var str = JSON.stringify({
                        "name": data.name,
                        "msg": data.msg,
                        "type": data.type
                    });
                    wsServer.broadcast(str);
                    break;
                case 'systemInfo':
                    var str = JSON.stringify({
                        "msg": data.msg,
                        "type": data.type
                    });
                    wsServer.broadcast(str);
                    break;
                case 'audioInfo':
                    var str = JSON.stringify({
                        "name": data.name,
                        "recordedBlobs": data.recordedBlobs,
                        "type": data.type
                    });
                    wsServer.broadcast(str);
                    break;

                default:
                    break;
            }
        } catch (e) {
            console.log('消息格式错误 消息内容 : ', message);
            console.log('解析错误 : ', e);
        }
    });

    /// 客户端关闭事件
    client.on('close', function (o) {
        try {
            console.log(`${client.clientId} from server: close `);

            var str = JSON.stringify({
                "msg": client.clientId + "已下线......",
                "type": "systemInfo"
            });
            wsServer.broadcast(str);
        }
        catch (e) {
            console.log(e);
        }
    });

});

module.exports = wsServer 